package at.guigu.web.servlet;

import at.guigu.pojo.Brand;
import at.guigu.service.BrandService;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/addServlet")
public class AddServlet extends HttpServlet {
    //1 创建一个私有的BrandService对象
    private BrandService brandService = new BrandService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //2 接收表单提交的JSON数据并封装为Brand对象
        /*request.getParameter不能接收JSON字符串数据
        String brandName = request.getParameter("brandName");
        String companyName = request.getParameter("companyName");
        String ordered = request.getParameter("ordered");
        String description = request.getParameter("description");
        String status = request.getParameter("status");*/
        //2.1 获取请求体数据
        BufferedReader br = request.getReader();
        //获取到的客户端发送的JSON字符串数据不论多长都是一行,所以读取一行即可
        String jsonStr = br.readLine();
        //2.2 将JSON字符串数据转为Java的Brand对象
        Brand brand = JSON.parseObject(jsonStr, Brand.class);

        //3 调用brandService完成添加
        brandService.add(brand);

        //4 响应成功标识
        response.getWriter().write("success");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}